﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class Get_OrdersController : UserController
    {
        public IOrdersService _orders { get; set; }
        public IExpressService _express { get; set; }
        public IPaymentService _payment { get; set; }
        [Authorize]
        [HttpGet]
        public IActionResult Get(int id)
        {
            //检查用户是否登录
            Users userModel = GetUserInfo();
            if (userModel == null)
            {
                return Ok(new { status = 0, msg = "用户尚未登录或已超时！" });
            }
            if (!_orders.Exists(id))
            {
                return Ok(new { status = 0, msg = "订单不存在！" });
            }
            var model = _orders.GetModel(id);
            if (model.user_id != userModel.id)
            {
                return Ok(new { status = 0, msg = "您所查看的并非自己的订单信息！" });
            }
            var payModel = _payment.GetModel(model.payment_id);
            if (payModel == null)
            {
                payModel = new Payment();
            }
            //根据订单状态和物流单号跟踪物流信息
            string expressdetail = "";
            if (model.status > 1 && model.status < 4 && model.express_status == 2 && model.express_no.Trim().Length > 0)
            {
                Express modelt = _express.GetModel(model.express_id);
                Orderconfig orderConfig = Common.XMLConfig.Orderconfig.loadConfig(_env.ContentRootPath);
                if (modelt != null && modelt.express_code.Trim().Length > 0 && orderConfig.kuaidiapi != "")
                {                    
                    string detail = KuaiDi100.Check(modelt.express_code, model.express_no, orderConfig.kuaidiid, orderConfig.kuaidikey, orderConfig.kuaidiapi);
                    if (detail != null)
                    {
                        expressdetail = Utils.ToHtml(detail);
                    }
                }
            }
            return Ok(new { status = 1, order = model, payment = payModel, express = expressdetail });
        }
    }
}